﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.IO;

namespace MyImage
{
    public partial class _Default : System.Web.UI.Page
    {

        protected System.Web.UI.WebControls.Image imgImage;
        private int THUMBNAIL_SIZE = 60;

        protected void Page_Load(object sender, EventArgs e)
        {


        }
        protected byte[] Bitmap2Byte(Bitmap bitmap)
        {
            try
            {
                MemoryStream memoryStream = new MemoryStream();
                byte[] byteResult = null;
                bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                byteResult = memoryStream.GetBuffer();

                bitmap.Dispose();
                if (memoryStream != null)
                    memoryStream.Close();

                return byteResult;
            }
            catch (Exception ex)
            {
                return null;
            }

        }
        protected void CreateImageFromByte(int id)
        {
            ParseImage.THUMBNAIL_SIZE = this.THUMBNAIL_SIZE;
            ParseImage.USE_SIZE_FOR_HEIGHT = false;
            imgImage = new System.Web.UI.WebControls.Image();
            //// set the source to the page that generates the thumbnail image
            imgImage.ImageUrl = ParseImage.PAGE_NAME + "?" +
               ParseImage.IMAGE_ID + "=" + id;

            previewImage.Controls.Clear();
            previewImage.Controls.Add(imgImage);

    


          


        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            // get name file and extension of file
            string pathFile = FileUpload1.PostedFile.ContentType;

            if (pathFile.ToLower().StartsWith("image"))
            {
                Bitmap bitmapImage = (Bitmap)System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
                int id = 0;

                int RowsAff = DataAcess.SaveImage(ref id, Bitmap2Byte(bitmapImage));
                if (RowsAff > 0)
                {
                    CreateImageFromByte(id);
                }
                else
                {
                    lblMessage.Text = "loi upload";
                }
            }
        }

    }
}
